package com.kx.game.center.serverDistribution;

import com.alibaba.fastjson.JSONObject;
import com.kx.game.center.global.GSServices;
import com.kx.game.center.redis.RedisConstant;
import com.redis.core.manager.RedisManager;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class EquilibriumDistribution implements ServerDistributionInterface{

    @Override
    public JSONObject execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        RedisManager redisManager = GSServices.redisServer.getRedisClient();
        Map<Object, Object> entries = redisManager.getRedisTemplate()
                .opsForHash().entries(RedisConstant.SERVER_CREATE_NUM);
        entries.remove(String.valueOf(GSServices.serverConfig.getFriendServerId()));
        List<Map.Entry<Object,Object>> list = new ArrayList(entries.entrySet());
        Collections.sort(list, (o1, o2) -> (Integer.parseInt(String.valueOf(o1.getValue())) - Integer.parseInt(String.valueOf(o2.getValue()))));
        String serverKey = String.valueOf(list.get(0).getKey());
        int num = Integer.parseInt(redisManager.hashGet(RedisConstant.SERVER_CREATE_NUM, serverKey, String.class));
        if (GSServices.serverConfig.getServerPlayerNum() > num){
            JSONObject jsonObject = GSServices.localManager.getGameServerInfo(serverKey);
            return GSServices.localManager.getJson(
                    ResponseState.SUCCESS,String.valueOf(jsonObject.get("ip")),String.valueOf(jsonObject.get("gamePort")));
        }else {
            return GSServices.localManager.getJson(ResponseState.SERVER_NUM_FULL,null, null);
        }
    }
}
